/* api */
import { getTaskPoolAuthUserList, getTaskPoolSubscriptionUserList, getCustomerTagTaskPoolCount, getTaskPoolList } from '@src/api/TaskApi'
/* components */
import TaskAllotMap from '@src/modules/task/components/TaskAllotModal/TaskAllotMap/TaskAllotMap.tsx'
import TaskAllotPoolNotification from '@src/modules/task/components/TaskAllotModal/TaskAllotPool/TaskAllotPoolNotification/TaskAllotPoolNotification.tsx'
import TaskAllotPoolInfo from '@src/modules/task/components/TaskAllotModal/TaskAllotPool/TaskAllotPoolInfo/TaskAllotPoolInfo.tsx'
import UserCard from '@src/modules/task/components/TaskAllotModal/UserCard/UserCard.tsx'
import TaskMapInfoWindow from '@src/modules/task/components/TaskAllotModal/TaskMapInfoWindow/TaskMapInfoWindow.tsx'
import TaskAllotExcutor from '@src/modules/task/components/TaskAllotModal/TaskAllotExcutor/TaskAllotExcutor.tsx'
/* enum */
import ComponentNameEnum from '@model/enum/ComponentNameEnum'
import EventNameEnum from '@model/enum/EventNameEnum'
import TaskStateEnum from '@model/enum/TaskStateEnum'
import { TaskPoolNotificationTypeEnum } from '@src/modules/task/components/TaskAllotModal/TaskAllotPool/TaskAllotPoolModel'
import { BaseSelectUserModeEnum } from '@src/component/common/BaseSelectUser/model/enum'
import { TaskVNodeTypeEnum } from '@src/modules/task/components/TaskAllotModal/TaskAllotModalModel'
/* entity */
import Customer from '@model/entity/Customer'
import CustomerAddress from '@model/entity/CustomerAddress'
import LoginUser from '@model/entity/LoginUser/LoginUser'
import Tag from '@model/entity/Tag/Tag'
import TaskPoolUser from '@model/entity/TaskPoolUser'
import TaskAllotUserInfo from '@model/entity/TaskAllotUserInfo'
import TaskType from '@model/entity/TaskType'
/* image */
// @ts-ignore
import { getOssUrl } from '@src/util/assets'
/* interface */
import { TaskAllotPoolInfoData } from '@src/modules/task/components/TaskAllotModal/TaskAllotPool/TaskAllotPoolInterface'
/* model */
import Page from '@model/Page'
import { getCustomerTagTaskPoolCountResult, getTaskPoolAuthUsersResult, getTaskPoolSubscriptionUsersResult, getTaskSearchListResult } from '@model/param/out/Task'
import { DepeMultiUserResult } from '@src/modules/task/components/TaskAllotModal/TaskAllotModalInterface'
/* vue */
import { Vue, Component, Prop, Ref, Emit } from 'vue-property-decorator'
import { CreateElement } from 'vue'
import { VNode } from 'vue'
/* sccss */
import '@src/modules/task/components/TaskAllotModal/TaskAllotPool/TaskAllotPool.scss'
/* types */
import StateColorMap from '@model/types/StateColor'
import TaskConfig from '@model/config/TaskConfig'
/* util */
import Log from '@src/util/log.ts'
import Platform, { isOpenData, isDevelopment } from '@src/util/platform'
import { findComponentUpward } from '@src/util/assist'
import { openTabForTaskView, openTabForCustomerView } from '@src/util/business/openTab'
import { fmt_number } from '@src/filter/fmt'
import { isBeforeTime } from 'pub-bbx-utils'
import { RESOURCE_PREFIX } from '@src/util/linkSwitch';
import i18n from '@src/locales'

import VC from '@model/VC'
import { MAX_SELECT_USER_COUNT } from '@src/model/const/Number'
import { chooseExUser } from '@model/config/SelectUserConfig'
import {
  TaskAllotServiceProviderEmitEventEnum
} from '@src/modules/task/components/TaskAllotModal/TaskAllotServiceProvider/TaskAllotServiceProviderModel'
import UiInput from '@src/component/ui/UiInput/UiInput'

const resourcePrefix = isDevelopment() ? '' : RESOURCE_PREFIX

/* @能力 */
const defaultAvatar = getOssUrl('/avatar.png')
import { useNewVue } from '@hooks/useNewVue'
const { extendVue } = useNewVue();
import { overlayFun, googleOverlayFun } from '@src/util/bMap';
let SquareOverlay:any

declare let AMap: any
declare let BMap: any
declare let google: any

// @ts-ignore
window.openTaskViewFunc = function openTaskViewFunc(taskId: string) {
  openTabForTaskView(taskId)
}
// @ts-ignore
window.openCustomerViewFunc = function openCustomerViewFunc(customerId: string) {
  openTabForCustomerView(customerId)
}


enum TaskAllotPoolEmitEventEnum {
  SetReason = 'setReason',
  SetCustomReason = 'setCustomReason',
  SetAtUsers = 'setAtUsers'
}

@Component({ 
  name: ComponentNameEnum.TaskAllotPool,
  components: {
    TaskAllotMap,
    TaskAllotPoolNotification,
    TaskAllotPoolInfo,
    UserCard,
    TaskMapInfoWindow,
    UiInput
  }
})
export default class TaskAllotPool extends VC {
  /* 工单池信息组件 */
  @Ref() readonly TaskAllotPoolInfoComponent!: TaskAllotPoolInfo
  
  /* 客户团队列表 */
  @Prop() readonly customerTags: Tag[] | undefined
  /* 是否显示协同人 */
  @Prop() readonly isShowSynergy: boolean | undefined
  /* 是否为转派 */
  @Prop() readonly isReAllot: boolean | undefined
  /* 转派原因 */
  @Prop() readonly reason: string | undefined
  /* 协同人列表 */
  @Prop() readonly synergyUserList: LoginUser[] | undefined
  /* 显示状态 */
  @Prop() readonly show: boolean | undefined
  /* 工作状态颜色数组 */
  @Prop() readonly stateColorMap: StateColorMap | undefined
  /* 选择的负责人信息 */
  @Prop() readonly selectedExcutorUser: TaskAllotUserInfo | undefined
  /* 工单信息 */
  @Prop() readonly task: any | undefined
  /* 工单设置 */
  @Prop() readonly taskConfig: TaskConfig | undefined
  /* 工单类型列表 */
  @Prop() readonly taskTypesMap: { [x: string]: TaskType} | undefined
  /* 转派选择的原因 */
  @Prop({ default: '' }) readonly customReason: string | undefined
  /* @人员 */ 
  @Prop() readonly atUsers: [] | undefined
  /*异常列表 */
  @Prop({ default: ()=>[] }) readonly backList: string[] | undefined
  /*判断是否配置 */ 
  @Prop() readonly systemAdmin: any | undefined
  /* 工单信息弹窗 */
  private AMapTaskInfoWindow: any = null
  /* 是否在地图显示工单池订阅用户 */
  private isShowMapTaskPoolSubscriptionUsers: boolean = false
  /* 是否在地图显示有权限接单用户 */
  private isShowMapTaskPoolAuthUsers: boolean = false
  /* 是否显示人员卡片信息 */
  private isShowUserCard: boolean = false
  /* 地图的id */
  private mapId: string = 'TaskAllotPoolMapContainer'
  /* 通知方式复选 */
  private notificationCheckd: TaskPoolNotificationTypeEnum[] = []
  /* 当前选择地图工单 */
  private selectedMapTask: any = {}
  /* 当前选择地图人员 */
  private selectedMapUser: LoginUser | null = null
  /* 工单池通知自定义人员 */
  private taskPoolNotificationUsers: LoginUser[] = []
  /* 工单池统计数据信息 */
  private taskPoolInfo: TaskAllotPoolInfoData = {
    taskPoolAllCount: 0,
    customerTeamUnAcceptCount: 0,
    subscriptionUserCount: 0,
    havePermissionUserCount: 0,
  }
  /* 工单池列表 */
  private taskPoolList: any[] = []
  /* 订阅用户page */
  private userSubscriptionPage: Page =  new Page()
  /* 有权限接单用户page */
  private userAuthPage: Page =  new Page()
  // 当前弹出的工单详情信息弹窗
  private taskInfoWindow = null
  private isMounted = false
  
  /** 
   * @description 工单信息中计划时间是否可以修改
   * 1. 工单状态是待指派或已拒绝
   * 3. 工单设置允许修改计划时间
  */
  get allowModifyPlanTime(): boolean {
    let states = [TaskStateEnum.CREATED.value, TaskStateEnum.REFUSED.value]
    let { state } = this.task
    return Boolean(this.taskConfig?.taskPlanTime === true && states.indexOf(state) >= 0)
  }
  
  /* 工单派单组件 */
  get TaskAllotModalComponent() {
    return findComponentUpward(this, ComponentNameEnum.TaskAllotModal) || {}
  }
  
  /* 客户 */
  get customer(): Customer {
    return this.TaskAllotModalComponent.customer || {}
  }
  
  /* 客户地址 */
  get customerAddress(): CustomerAddress {
    return this.customer.customerAddress || new CustomerAddress()
  }
  
  /* 客户团队名称列表 */
  get customerTagNames(): string[] {
    return this.customerTags ? this.customerTags.map(tag => tag.tagName || '') : []
  }
  
  /* 是否开启 按服务团队划分工单池 */
  get isPoolByTag(): boolean {
    return this.taskConfig?.poolByTag === true
  }
  
  /**
   * @description 转派说明是否必填
   */
  get reallotRemarkNotNull(): boolean {
    return this.taskConfig?.reallotRemarkNotNull === true
  }
  
  /**
   * @description 转派原因变化事件
   */
  @Emit(TaskAllotPoolEmitEventEnum.SetReason)
  public reasonChangedHandler(reason: string): string {
    return reason
  }
  /**
   * @description 转派原因at人员
   */
  @Emit(TaskAllotPoolEmitEventEnum.SetAtUsers)
  public atUsersChangedHandler(users: []): [] {
    return users
  }
  
  @Emit(TaskAllotPoolEmitEventEnum.SetCustomReason)
  /**
   * @description  转派说明
   */
  public customReasonChangedHandler(customReason: string):string {
    return customReason
  }
  /** 
   * @description 构建标记
  */
  private buildMarkers(amap: any): void {
    // 构建工单池订阅人员标记
    this.isShowMapTaskPoolSubscriptionUsers && this.buildUserMarkers()
    // 构建有权限接单人员标记
    this.isShowMapTaskPoolAuthUsers && this.buildUserMarkers(false)
    // 构建工单标记
    this.buildTaskMarkers()
  }
  
  /** 
   * @description 构建人员标记
   * @param {Object} amap 高德地图对象
   * @param {Object} infoWindow 高德地图窗口对象
   * @param {Boolean} isSubscription 是否是订阅工单池用户列表
  */
  public buildUserMarkers(isSubscription: boolean = true): void {
    const amap = this.$refs.TaskAllotMap.AMap
    let userPageList = isSubscription ? this.userSubscriptionPage.list : this.userAuthPage.list 
    if (userPageList.length <= 0) {
      return Log.warn('userPage.list is empty', this.buildUserMarkers.name)
    }
    let userMarkListKey = isSubscription ? 'taskpoolAlotuser' : 'taskpoolAlotuserAuth'
    let userMarkList:any[] = []
    userPageList = isSubscription ? this.isShowMapTaskPoolSubscriptionUsers ? this.userSubscriptionPage.list : [] : this.isShowMapTaskPoolAuthUsers ? this.userAuthPage.list : []
    userPageList.forEach((item, index)=>{
      let user: LoginUser = item.user
      let { longitude, latitude } = user
      if (!longitude || !latitude) return
      userMarkList.push({
        lng:longitude,
        lat:latitude,
        size:{
          x:10,
          y:10
        },
        markInfo:`<img class="${'size-42-r'}" src="${user.head || defaultAvatar}" >`,
        markClickFn:()=>{
          this.selectedMapUser = user;
          this.$nextTick(() => {
            this.isShowUserCard = true
          })
        },
        markKey:user.userId,
        markListKey:userMarkListKey
      })
    })
    if(!userMarkList.length) return amap.clearListMark(userMarkListKey)
    amap.setListMark(userMarkList, true, false)
    
    
  }
  
  /** 
   * @description 构建工单标记
   * @param {Object} amap 高德地图对象
   * @param {Object} infoWindow 高德地图窗口对象
  */
  public buildTaskMarkers(amap: any): void {
    if (this.taskPoolList.length <= 0) {
      return Log.warn('taskPoolList is empty', this.buildTaskMarkers.name)
    }
    let taskMark = []
    
    this.taskPoolList.forEach((task: any) => {
      let { longitude, latitude } = task?.address || {}
      if (!longitude || !latitude) return
      let _this = this;
      taskMark.push({
        lng:longitude,
        lat:latitude,
        size:{
          x:24,
          y:24
        },
        markInfo:`<i class="iconfont task-pool-icon icon-address ${task.isTimeout ? 'task-pool-timeout' : ''}"></i>`,
        infoWindow:'<div>test</div>',
        markClickFn:()=>{
          this.$set(this, 'taskInfoWindow', task)
          _this.$nextTick(()=>{
            _this.$refs.TaskAllotMap.AMap.openInfoWindow({markKey:task.taskNo,  markListKey:'task', content:_this.$refs.infoWindowComponent})
          })
        },
        markKey:task.taskNo,
        markListKey:'task'
      })
  
    })
    if(!taskMark.length) return this.$refs.TaskAllotMap.AMap.clearListMark('task')
    this.$refs.TaskAllotMap.AMap.setListMark(taskMark, true, false)
  }
  
  /** 
   * @description 选择工单池通知其他人
  */
  public chooseTaskPoolNotificationUsers(): void {
    let options = {
      title: i18n.t('task.tip.taskAllotModalTip15'),
      selectedUsers: this.taskPoolNotificationUsers,
      max: 14,
      unique: false,
      mode: BaseSelectUserModeEnum.Filter
    };
    
    // @ts-ignore
    this.$fast.select.multi.user(options)
      .then((result: DepeMultiUserResult) => {
        let isSuccess = result.status == 0
        if (!isSuccess) return
        
        // 工单池通知人员赋值
        this.taskPoolNotificationUsers = result?.data?.users || []
         // 判断是否选中 可以通知其他人
        if (!this.notificationCheckd || !this.notificationCheckd.includes(TaskPoolNotificationTypeEnum.SendToOtherUser)) {
          this.notificationCheckd.push(TaskPoolNotificationTypeEnum.SendToOtherUser)
        }
      })
      .catch((err: any) => {
        console.error(err)
      })
  }
  
  /** 
   * @description 关闭用户卡片
  */
  private closeUserCard() {
    this.isShowUserCard = false
  }
  
  /**
   * @description 关闭地图标记弹窗
   */
  private closeInfoWindowHandler() {
    this.AMapTaskInfoWindow?.close()
  }

  /**
   * @description 更新计划时间操作
   * @param {string} newPlanTime 新计划时间值
   * @return {void}
   */  
   public updatePlanTime(newPlanTime: string): void {
    this.taskPoolList.forEach(task => {
      // @ts-ignore
      if (this.taskInfoWindow && task.id == this.taskInfoWindow.id) {
        task.planTime = newPlanTime;
      }
    })
    
    this.$message.success(i18n.t('common.base.tip.editSuccess') as string)
  }

  /**
   * @description 更新计划开始和结束时间操作
   * @param {string} newPlanTime 新计划时间值
   * @return {void}
   */  
  public updateCalendarPlanTime(newPlanTime: object): void {
    this.taskPoolList.forEach(task => {
      // @ts-ignore
      if (this.taskInfoWindow && task.id == this.taskInfoWindow.id) {
        // @ts-ignore
        if(task.planStartTimeShow) task.planStartTime = newPlanTime?.start;

        // @ts-ignore
        if(task.planEndTimeShow) task.planEndTime = newPlanTime?.end;
      }
    })
    
    this.$message.success(i18n.t('common.base.tip.editSuccess') as string)
  }
  
  /** 
   * @description 获取有权限接单用户列表
   * -- 内部调用的
  */
  public fetcAuthhUsers(): Promise<any> {
    Log.succ(Log.Start, this.fetcAuthhUsers.name)
    
    let params = {
      taskId: this.task?.id || '',
    }
    
    return (
      getTaskPoolAuthUserList(params).then((result: getTaskPoolAuthUsersResult) => {
        let isSuccess = result.succ
        if (!isSuccess) {
          return Platform.alert(result.message)
        }
        
        this.userAuthPage.list = result.data || []
        
        Log.succ(Log.End, this.fetcAuthhUsers.name)
      })
    )
  }
  
  /** 
   * @description 获取订阅用户列表
   * -- 内部调用的
  */
  public fetchSubscriptionUsers(): Promise<any> {
    Log.succ(Log.Start, this.fetchSubscriptionUsers.name)
    
    return (
      getTaskPoolSubscriptionUserList().then((data: getTaskPoolSubscriptionUsersResult) => {
        let isSuccess = data.success
        if (!isSuccess) {
          return Platform.alert(data.message)
        }
        
        this.userSubscriptionPage.list = data.result || []
        
        Log.succ(Log.End, this.fetchSubscriptionUsers.name)
      })
    )
  }
  
  /** 
   * @description 查询客户团队工单池数量
  */
  private fetchCustomerTagTaskPoolCount() {
    Log.succ(Log.Start, this.fetchCustomerTagTaskPoolCount.name)
    
    let params = {
      cusTagIds: this.customer.tags?.map((tag: Tag) => tag.id) || []
    }
    
    return (
      getCustomerTagTaskPoolCount(params)
      .then((data: getCustomerTagTaskPoolCountResult) => {
        let isSuccess = data.success
        if (!isSuccess) {
          return Platform.alert(data.message)
        }
        
        this.taskPoolInfo.customerTeamUnAcceptCount = data.result
        
        Log.succ(Log.End, this.fetchCustomerTagTaskPoolCount.name)
      })
      .catch((err: any) => {
        console.error(err)
      })
    )
  }
  
  /** 
   * @description 获取工单池列表
  */
  private fetchTaskPoolList() {
    return (
      getTaskPoolList({ ids: [], page: 1, pageSize: 1000 }).then((data: getTaskSearchListResult) => {
        let isSuccess = data.success
        if (!isSuccess) {
          return Platform.alert(data.message)
        }
        
        // 工单池列表数据
        this.taskPoolList = data?.result?.content.map((task: any) => {
          let isTimeout = isBeforeTime(task.overTime)
          task.isTimeout = isTimeout
          task.id = task.id || task.taskId || task.taskUUID || ''
          return task
        }) || []
        // 工单池总量
        this.taskPoolInfo.taskPoolAllCount = fmt_number(data.result?.totalElements, '')
        
      })
    )
  }
  
  private handleAddNotificationUser() {
    // 选择工单池通知其他人
    this.chooseTaskPoolNotificationUsers()
  }
  
  /** 
   * @description 工单池详细信息 订阅工单池用户 checkbox变化
  */
  private handlerTaskPoolInfoSubscriptionChanged(value: boolean): void {
    this.isShowMapTaskPoolSubscriptionUsers = value
    this.TaskAllotPoolInfoComponent?.$nextTick(() => {
      this.buildUserMarkers()
    })
  }
  
  /** 
   * @description 工单池详细信息 有权限接单用户 checkbox变化
  */
  private handlerTaskPoolInfoAuthChanged(value: boolean): void {
    this.isShowMapTaskPoolAuthUsers = value
    this.TaskAllotPoolInfoComponent?.$nextTick(() => {
      this.buildUserMarkers(false)
    })
  }
  
  /**
   * @description 初始化 获取用户列表并且初始化地图
  */
  public initialize(): void {
    Log.succ(Log.Start, this.initialize.name)
    
    this.userSubscriptionPage = new Page()
    this.userAuthPage = new Page()
    
    // 查询工单池工单列表
    this.fetchTaskPoolList().then(() => {
      this.mapInit()
    })
    // 查询有权限接单人员列表
    this.fetcAuthhUsers()
    // 查询订阅工单池人员列表
    this.fetchSubscriptionUsers()
    // 查询客户团队统计工单池数量
    this.isPoolByTag && this.fetchCustomerTagTaskPoolCount()
  }
  
  /**
   * @description 地图初始化事件
  */
  public mapInit(): void {
    try {
      // @ts-ignore
      // this.$refs.TaskAllotMap.outsideMapInit()
      this.buildMarkers()
    } catch (error) {
      console.warn('TaskAllotPool -> mapInit -> error', error)
    }
  }
  
  /** 
   * @description 工单池通知方式改变
  */
  private onNotificationCheckedChanged(value: TaskPoolNotificationTypeEnum[]): void {
    this.notificationCheckd = value
  }
  
  /** 
   * @description 构建数据
   * -- 支持外部调用的
  */
  public outsideBuildData(): { checked: TaskPoolNotificationTypeEnum[], users: LoginUser[] } {
    return {
      checked: this.notificationCheckd,
      users: this.taskPoolNotificationUsers
    }
  }
  
  /**
   * @description 移除通知用户
  */
  private removeNotificationUser(user: LoginUser) {
    this.taskPoolNotificationUsers = (
      this.taskPoolNotificationUsers
      .filter((notificationUser: LoginUser) => {
        return notificationUser.userId !== user.userId
      })
    )
  }
  
  /** 
   * @description 渲染选择通知用户
  */
  private renderNotificationAddUser() {
    let isNotificationUsersEmpty = this.taskPoolNotificationUsers.length <= 0
    
    return (
      <div class='task-allot-pool-notification-input' onClick={() => this.handleAddNotificationUser()}>
        {
          isNotificationUsersEmpty 
          ? <span class='task-allot-pool-notification-placeholder'>{i18n.t('common.placeholder.selectSomething', {0: i18n.t('common.base.person')})}</span>
          : (
            this.taskPoolNotificationUsers.map((user: LoginUser) => {
              return (
                <el-tag key={user.userId} size='mini' disable-transitions closable type='info' onClose={() => this.removeNotificationUser(user)}>
                  {isOpenData ? (
                    <open-data type="userName" openid={user.staffId}></open-data>
                  ) : (
                    user.displayName
                  )}
                </el-tag>
              )
            })
          )
        }
      </div>
    )
  }
  
  /**
   * @description 渲染工单派单转派原因
   */
   public head(src:string):String{
    if (!src) return defaultAvatar
    return src
  }
  private renderTaskAllotReason(): VNode | null {
    const scopedSlots ={
      item: (props: any) => {
        return (
          <div>
            <img src={this.head(props.user.head)} />
            <span>{props.user.displayName}</span>
          </div>
        )
      },
    }
    return (
      // <el-input
      //   autocomplete="off"
      //   class='task-allot-reason-input'
      //   placeholder={`${this.reallotRemarkNotNull ? '[必填]' : '[选填]'} 转派说明`}
      //   type='text'
      //   value={this.reason}
      //   onInput={(value: string) => this.reasonChangedHandler(value)}
      // />
      <biz-at-textarea 
        class="biz-at-textarea ATtextarea" 
        ref="atTextarea" 
        search-url="/message/user/lists" 
        name-key="displayName" 
        value={this.reason} 
        onSetUsers={(users: []) =>this.atUsersChangedHandler(users)}
        scopedSlots={scopedSlots}
        direction="bottom"
        >
          <el-input
            ref="editor"
            autocomplete="off"
            class='task-allot-reason-input TransferInstructions'
            placeholder={i18n.t('task.tip.taskAllotModalTip12', {data: this.reallotRemarkNotNull ? i18n.t('common.base.isRequire') : i18n.t('common.base.optional')})}
            type='textarea'
            resize="none"
            value={this.reason}
            autosize={{ minRows: 1, maxRows: 2 }}
            onInput={(value: string) => this.reasonChangedHandler(value)}
          />
        {/* <textarea  onInput={(event: any) =>this.reasonChangedHandler(event.target.value)} maxlength="500" rows="1"></textarea> */}
      </biz-at-textarea>
    )
  }
  
  /**
   * @description 渲染工单派单转派原因行
   * -- TODO: 此法不建议
   */
  private renderTaskAllotReasonRow(): VNode | null {
    const taskAllotExcutor: TaskAllotExcutor = new TaskAllotExcutor()
    
    return (
      <div class='task-allot-reason-row task-allot-executor-header'>
        {this.isReAllot && <div class="task-flex task-ai task-mr12">
        {/* 派单到工单池——转派原因 */}
        { this.reallotRemarkNotNull ? <span class="task-cef">*</span> : null }
          {i18n.t('task.list.displayName.transferReason')}： 
          <el-select style='width:240px;' value={this.customReason} placeholder={i18n.t('task.tip.taskAllotModalTip13', {data: this.reallotRemarkNotNull ? i18n.t('common.base.isRequire') : i18n.t('common.base.optional')})}  onChange={(v: string) => this.customReasonChangedHandler(v)}>
            {
              this.backList && this.backList.map(item => {
                return (
                  <el-option
                    key={item}
                    label={item}
                    value={item}
                  />
                )
              })
            }
          </el-select>
          {
            this.systemAdmin ? <div class="task-font12 task-c13 task-ml12 task-pointer" onClick={() => {window.location.href = `${resourcePrefix}/setting/task/taskSet`}}>
              <el-tooltip class="item" effect="dark" content={i18n.t('task.goSetReason')} placement="top">
                <span class="iconfont icon-xitongguanli" style="color:#6c6c6d;"></span>
              </el-tooltip>
              
            </div> : null
          }
        </div>}
        {this.renderTaskAllotExecutorHeaderRow(`${i18n.t('task.synergies')}：`, this.renderSynergySelect())} 
      </div>
    )
  }


  public renderTaskAllotExecutorHeaderRow(label: string, node: VNode | null, style: string = ''): VNode {
    return (
      <div class='task-allot-executor-header-row' style={style}>
        <span class='task-allot-executor-header-row-label'>
          { (this.reallotRemarkNotNull && label !== TaskVNodeTypeEnum.Synergies) ? <span class="task-cef">*</span> : null }
          {label}
        </span>
        {node}
      </div>
    )
  }

  public setInfoWindowDom(){
    const _this = this;
    return (
      <div class="need-hide-in-oversize">
        <div class="task-map-info-window" ref='infoWindowComponent'>
          {_this.taskInfoWindow && <task-map-info-window
            show="true"
            showModifyPlanTime={_this.allowModifyPlanTime}
            task={_this.taskInfoWindow}
            onClose={() => _this.closeInfoWindowHandler()}
            onPlanTimeChange={(planTime: string) => this.updatePlanTime(planTime)}
            onUpdateCalendarPlanTime={(newCalendarPlan: object) => this.updateCalendarPlanTime(newCalendarPlan)}
          />
          }
        </div>
      </div>
    )
  }
    /**
   * @description 渲染协同人
  */
  public renderSynergySelect(): any | null {
      if (!this.synergyUserList) return null
  
      // 是否存在协同人
      let isHaveSynergyUser = this.synergyUserList.length > 0
      // 需要显示的第一个协同人
      let user: any =this.synergyUserList.length? this.synergyUserList[0] : {}
      // 是否有更多的协同人 (大于1个)
      let isMoreOne = Boolean(this.synergyUserList && this.synergyUserList.length > 1)
      // 样式类名
      let classNames: string[] = ['task-allot-sysnergy-select']
  
      return (
        <div class={classNames} onClick={() => this.chooseSynergyUser()}>
          <ui-input style={`min-height:${this.synergyUserList.length > 5 ? '60px' : '32px'};width:400px;`} hideIcon placeholder={i18n.t('common.placeholder.selectSomething', {0: i18n.t('task.synergies')})}>
            {
              isHaveSynergyUser && (
                this.synergyUserList.map(item=>{
                  return (
                    <el-tag key={item?.userId} size='mini' disable-transitions closable type='info' onClose={() => this.removeSynergyUser(item)}>
                      {isOpenData ? <open-data type="userName" openid={item.staffId}></open-data> : item.displayName}
                    </el-tag>
                  )
                })
              )
            }
          </ui-input>
        </div>
      )
  }
    /** 
   * @description 选择协同人
  */
  public chooseSynergyUser(): void {
      let options = {
        title: i18n.t('common.placeholder.selectSomething', {0: i18n.t('task.synergies')}),
        selectedUsers: this.synergyUserList,
        max: MAX_SELECT_USER_COUNT,
        unique: false,
        haveRole: true,
        mode: BaseSelectUserModeEnum.Filter,
        ...chooseExUser
      };
  
      // @ts-ignore
      this.$fast.select.multi.user(options)
        .then((result: DepeMultiUserResult) => {
          let isSuccess = result.status == 0
          if (!isSuccess) return
  
          // 协同人赋值
          this.synergyUserListChangedHandler(result?.data?.users || [])
        })
        .catch((err: any) => {
          console.error(err)
        })
  }
  /**
   * @description 移除协同人
   */
  public removeSynergyUser(user: LoginUser) {
    this.synergyUserCloseHandler(user)
  }

    /**
   * @description 协同人用户删除事件
   */
  @Emit(TaskAllotServiceProviderEmitEventEnum.DeleteSynergyUser)
  public synergyUserCloseHandler(user: LoginUser): LoginUser {
    return user
  }
    /**
   * @description 协同人用户列表变化事件
   */
  @Emit(TaskAllotServiceProviderEmitEventEnum.SetSynergys)
  public synergyUserListChangedHandler(users: LoginUser[]): LoginUser[] {
    return users
  }
  
  actived(){
    if(this.isMounted){
      this.mapInit()
    }
  }
  mounted() {
    this.initialize()
    this.isMounted = true
  }
  
  render(h: CreateElement) {
    const basePanelAttrs = {
      on: {
        'update:show': (show: boolean) => {
          // this.isShowUserCard = show
        }
      }
    }
    
    return (
      <div class={ComponentNameEnum.TaskAllotPool}>
        { this.renderTaskAllotReasonRow() }
        {/* 派单到工单池——转派说明 */}
        { this.isReAllot && <div class="task-allot-executor-header">
            {this.renderTaskAllotExecutorHeaderRow(TaskVNodeTypeEnum.AllotReason, this.renderTaskAllotReason(), 'flex:0 1 80%;') }
          </div> 
        }
        { this.setInfoWindowDom() }

        <task-allot-pool-info
          ref='TaskAllotPoolInfoComponent' 
          hideCustomerTagInfo={!this.isPoolByTag}
          stateColorMap={this.stateColorMap}
          info={this.taskPoolInfo}
          checked={{
            subscription: this.isShowMapTaskPoolSubscriptionUsers,
            auth: this.isShowMapTaskPoolAuthUsers
          }}
          users={{
            subscription: this.userSubscriptionPage.list,
            auth: this.userAuthPage.list
          }}
          onSubscriptionChange={(value: boolean) => this.handlerTaskPoolInfoSubscriptionChanged(value)}
          onAuthChange={(value: boolean) => this.handlerTaskPoolInfoAuthChanged(value)}
        />
        
        <task-allot-map
          ref='TaskAllotMap' 
          idName={this.mapId}
          taskTypesMap={this.taskTypesMap}
        />
        
        <task-allot-pool-notification
          checked={this.notificationCheckd} 
          checkedChangeFunc={(value: TaskPoolNotificationTypeEnum[]) => this.onNotificationCheckedChanged(value)}
          slotDefault={this.renderNotificationAddUser}
        >
        </task-allot-pool-notification>
        
        <div class='task-allot-user-content'>
          {this.isShowUserCard && (
            <base-panel width='470px' show={this.isShowUserCard} {...basePanelAttrs}>
              <user-card
                customer={this.customer}
                customerTagNames={this.customerTagNames}
                emitEventComponentName={ComponentNameEnum.TaskAllotPool}
                isReAllot={this.isReAllot}
                stateColorMap={this.stateColorMap}
                showExecutorButton={false}
                showSynergyButton={this.isShowSynergy}
                task={this.task}
                userId={this.selectedMapUser?.userId}
                onClose={() => this.closeUserCard()}
              />
            </base-panel>
          )}
        </div>
        
      </div>
    )
  }
  
}

